/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.axcc.srvaxcc.dao.impl;

import com.axcc.srvaxcc.dao.LoginDao;
import com.axcc.svraxcc.entitys.Agent;
import com.axcc.svraxcc.entitys.LoginAgent;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Christopher Garrido
 */
@Repository
public class LoginDaoImpl extends SimpleJdbcDaoSupport implements LoginDao {

    private static org.slf4j.Logger log = LoggerFactory.getLogger(LoginDaoImpl.class);

    @Autowired
    public LoginDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }

    @Override
    public Integer create(LoginAgent loginAgent) {

        String query_sql = "INSERT INTO `aaccmod`.`tbRegister` (`idRegister`,`idAgent`,`idTimes`,"
                + "`Disposition`,`TimeMark`,`DateMark`) VALUES (?,?,?,?,?,?);";
        // disposicion 0
        getJdbcTemplate().update(query_sql, 0, loginAgent.getIdAgent(), loginAgent.getIdTimes(), 0, loginAgent.getTimeMark(), loginAgent.getDateMark());
        return getSimpleJdbcTemplate().queryForInt("select last_insert_id()");
    }

    @Override
    public List allLoginDay(String dateMark) {
        return null;
    }

    @Override
    public Integer loginAgent(LoginAgent loginAgent) {

        String query_sql = "UPDATE `aaccmod`.`tbAgent` SET `isLogged` = ? WHERE `idAgent` = ?;";
        getJdbcTemplate().update(query_sql, 1, loginAgent.getIdAgent());
        return 1;
    }

    @Override
    public Integer validAgent(LoginAgent loginAgent) {
        Agent agentValid;

        String query_sql = "SELECT `idAgent`,`isLogged`  FROM `aaccmod`.`tbAgent` "
                + "WHERE `idAgent` = ?";

        try {
            agentValid = getSimpleJdbcTemplate().queryForObject(query_sql,
                    new BeanPropertyRowMapper<Agent>(Agent.class), loginAgent.getIdAgent());
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
        if (agentValid == null) {
            return 1;
        } else if (!agentValid.getIsLogged()) {
            return 10;
        } else if (agentValid.getIsLogged()) {
            return 11;
        }
        return 1;
    }

    @Override
    public Integer unLoginAgent(LoginAgent loginAgent) {
        String query_sql = "UPDATE `aaccmod`.`tbAgent` SET `isLogged` = ? WHERE `idAgent` = ?;";
        getJdbcTemplate().update(query_sql, 0, loginAgent.getIdAgent());
        return 0;
    }
}
